package com.coocaa.daemon.autoup;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.RemoteException;

import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LiteURI;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.litecontent.LiteContentServiceConnecter;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.AppData;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.RP_Installed_Apps;
import com.coocaa.x.service.litedaemon.LiteDaemon;
import com.coocaa.x.service.litedb.data.client.LiteDBSupport;
import com.tianci.appstore.ui.list.bootsetting.AutoStartDB;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xfk on 2015/9/1.
 */
public class AutoUpController extends LiteDaemon {
    private static LiteDaemonInfo info = null;
    private static String tag = "AutoUpController";

    static {
        info = new LiteDaemonInfo();
        info.id = "com.coocaa.daemon.autoup.AutoUpController";
        info.name = "AutoUpController";
    }

    public AutoUpController() {
        super(info);
    }

    @Override
    protected void onCreate(Context context) {
        this.mContext = context;
        final PackageManager pm = mContext.getPackageManager();
        LogUtils.i(tag, "AutoUpController start.");
        new Thread("ToastUIStub InitThread") {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                while (true) {
                    LogUtils.i(tag, "AutoUpController thread start 4");
                    List<ComponentName> names = Android.getComponentNames(mContext,
                            Intent.ACTION_BOOT_COMPLETED);
                    List<ComponentName> _names = new ArrayList<ComponentName>();

                    try {
                        LiteURI uri = LiteURI.create("apps://com.coocaa.app/installed_apps");
                        uri.addParams("filter", "autostart");
                        String result = LiteContentServiceConnecter.getService().call(uri.toString());
                        if (result != null) {
                            RP_Installed_Apps rp = RP_Installed_Apps.parseJObject(result, RP_Installed_Apps.class);
                            if (rp.error_code == 0 && rp.resource != null
                                    && rp.resource.total_count > 0) {
                                for (AppData item : rp.resource.resource_items) {
                                    String pkg = item.info.pkgName;
                                    if (pkg.equals("com.tianci.appstore") || item.info.isSystemApp)
                                        continue;

                                    for (ComponentName cn : names) {
                                        if (cn.getPackageName().equals(pkg)) {
                                            _names.add(cn);
                                            break;
                                        }
                                    }
                                }
                            }
                        } else {
                            LogUtils.i(tag, "result is null.");
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }

                    List<String> userEnableList = new ArrayList<String>();
                    try {
                        AutoStartDB ad = new AutoStartDB();
                        List<LiteDBSupport> list =  ad.select(null, null, null, " isEnable = ? ", "true");
                        LogUtils.i(tag, "user enable pkg size = "+list.size());
                        for(LiteDBSupport db : list)
                        {
                            AutoStartDB ad2 = (AutoStartDB)db;
                            userEnableList.add(ad2.pkg);
                            LogUtils.i(tag, "user enable pkg: "+ad2.pkg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    for (ComponentName name : _names) {
                        String pkg = name.getPackageName();
                        int val = Android.getComponentEnabledSetting(mContext, name);
                        LogUtils.i(tag, "boot up pkg = "+name+",  enable = "+val);
                        if(userEnableList.contains(pkg))
                        {
                            LogUtils.i(tag, "continue "+pkg);
                            continue;
                        }

                        if (val == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                                || val == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT)
                        {
                            LogUtils.i(tag, "ComponentName disEnabled: "+name);
                            if(setOneDisEnable(name) == false) {
                                try {
                                    Thread.sleep(20);
                                } catch (InterruptedException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                setOneDisEnable(name);
                            }
                        }
                    }

                    try {
                        Thread.sleep(1000 * 60 * 10);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    @Override
    protected void onDestroy() {

    }

    public synchronized boolean setOneDisEnable(ComponentName name) {
        Android.setComponentEnabledSetting(mContext, name,
                 PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
        if(Android.getComponentEnabledSetting(mContext,name ) == PackageManager.COMPONENT_ENABLED_STATE_DISABLED)
            return false;
        else
            return true;
    }
}
